#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import time
from functools import wraps

from fastapi.encoders import jsonable_encoder
from loguru import logger
from pydantic import BaseModel

from app.common.response import ResponseResult

# def responseBody(func):
#     @wraps(func)
#     async def wrapper(*args, **kwargs):
#         if asyncio.iscoroutinefunction(func):
#             result = await func(*args, **kwargs)
#         else:
#             result = func(*args, **kwargs)
#
#         if issubclass(type(result), BaseModel):
#             return ResponseResult(code='1000', msg='成功', data=result)
#         else:
#             responseResult = ResponseResult(code='1000', msg='成功')
#             responseResult.data = jsonable_encoder(result)
#             return responseResult
#     return wrapper

def responseBody(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if asyncio.iscoroutinefunction(func):
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            future = asyncio.ensure_future(func(*args, **kwargs))
            result = loop.run_until_complete(future)
            loop.close()
        else:
            result = func(*args, **kwargs)

        if issubclass(type(result), BaseModel):
            return ResponseResult(code='1000', msg='成功', data=result)
        else:
            responseResult = ResponseResult(code='1000', msg='成功')
            responseResult.data = jsonable_encoder(result)
            return responseResult
    return wrapper


def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()   # 记录开始时间
        result = func(*args, **kwargs)  # 执行函数
        elapsed_time = time.time() - start_time   # 计算耗时
        logger.info(f"{func.__name__} took {elapsed_time:.6f}s to execute.")
        return result
    return wrapper